<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        {{ isMerchant ? '申请运营商' : '编辑运营商' }}
      </div>
      <i-form
        ref="form"
        class="merchant-add__form"
        :items="formItems"
        :model="form"
        :rules="rules"
        label-width="160px"
      >
        <template slot="address">
          <el-form-item label="选择地区" prop="area" required>
            <HycAddressCascader ref="area" v-model="form.area" />
          </el-form-item>
        </template>
        <template slot="defaultPwd">
          <el-form-item prop="password" label="设置密码">
            <DefaultPwd
              v-model="form.password"
              placeholder="请输入密码"
              default-pwd="user_123456"
              @changeDefaultPwd="handleUserDefaultPwd"
              :clearable="true"
            />
          </el-form-item>
        </template>
        <template slot="splitCalcMethod">
          <el-form-item label="平台分账模式" prop="splitCalcMethod">
            <el-radio-group v-model="form.splitCalcMethod">
              <el-radio :label="'NO_ELECTRICITY'">成本前</el-radio>
              <el-radio :label="'WITH_ELECTRICITY'">成本后</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <template slot="cooperationUrl">
          <el-form-item label="合作协议" prop="cooperationUrl">
            <hyc-form-upload
              ref="bl_pic"
              v-model="form.cooperationUrl"
              :upload-data="stationImgData"
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template slot="licenseUrl">
          <el-form-item label="营业执照" prop="licenseUrl">
            <hyc-form-upload
              ref="bl_pic"
              v-model="form.licenseUrl"
              :upload-data="stationImgData"
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
        <template
          v-if="createrType == 'SELF_OPERATION_ADMIN'"
          slot="splitValue"
        >
          <el-form-item label="分账比例" prop="splitValue">
            <div style="display: flex">
              <el-input
                placeholder="请输入分账比例"
                v-model="form.splitValue"
              />
              %
            </div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="user-merchant-add__submit">
      <el-button v-loading="loading" @click="handleSubmit" type="success">
        确认
      </el-button>
      <el-button @click="handleReset" type="warning"> 重置 </el-button>
    </div>
  </div>
</template>
<script>
import {
  getMerchantAllRoles,
  updateMerchant,
  subMerchantApply,
  queryMerchant,
} from '@/api/user'
import DefaultPwd from '@/components/DefaultPwd'
import md5 from 'md5'
import formValidate from '@/utils/validate'
import HycFormUpload from '@/components/hycFormUpload'
import HycAddressCascader from '@/components/hycAddressCascader'
import { cloneDeep } from 'lodash'
import Big from 'big.js'

export default {
  name: 'merchantAdd',
  components: { HycAddressCascader, DefaultPwd, HycFormUpload },
  computed: {
    isMerchant() {
      return (
        this.$store.getters.roleType === 'MERCHANT' ||
        this.$store.getters.roleType === 'SELF_OPERATION_MERCHANT'
      )
    },
    isEdit() {
      return !!this.$route.params.userId
    },
  },
  data() {
    return {
      loading: false,
      stationImgData: { fileType: 'IMAGE' },
      createrType: '',
      form: {},
      rules: {
        userName: [{ validator: formValidate('validateAdministrator') }],
        mobile: [{ validator: formValidate('validateMobile') }],
        serviceMobile: [{ validator: formValidate('validateServiceMobile') }],
        area: [{ required: true, message: '请选择地区' }],
        password: [{ validator: formValidate('validatePassword') }],
        confirmPassword: [
          {
            validator: (...args) => {
              if (args[1] !== this.form.password) {
                args[2](new Error('两次密码不一致!'))
              } else {
                args[2]()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        splitCalcMethod: [{ required: true, message: '请选择' }],
      },
      formItems: [],
    }
  },
  mounted() {
    this.createrType = this.$store.getters.roleType
    const formItem = [
      {
        label: '运营商名',
        type: 'text',
        value: 'userName',
        maxlength: 16,
        required: true,
        'show-word-limit': true,
        clearable: true,
      },
      {
        label: '手机号',
        type: 'text',
        value: 'mobile',
        clearable: true,
        required: true,
        placeholder: '手机号码为运营商后台系统登录账户',
      },
      {
        label: '客服电话',
        type: 'text',
        value: 'serviceMobile',
        clearable: true,
        required: true,
      },
      {
        slot: 'address',
      },
      {
        label: '角色',
        type: 'select',
        options: [],
        value: 'roleId',
        clearable: true,
        required: true,
      },
      {
        slot: 'splitValue',
      },
      {
        label: '管理员姓名',
        type: 'text',
        value: 'name',
        clearable: true,
        required: true,
      },
      {
        slot: 'defaultPwd',
      },
      {
        label: '确认密码',
        type: 'password',
        value: 'confirmPassword',
        'show-password': true,
        clearable: true,
        autoComplete: 'off',
      },
      {
        label: '平台分账比例（%）',
        type: 'text',
        value: 'splitValue',
        clearable: true,
        required: true,
        placeholder: '请输入最小值为0；最大值为100的数字',
      },
      {
        slot: 'splitCalcMethod',
      },
      {
        slot: 'cooperationUrl',
      },
      {
        slot: 'licenseUrl',
      },
    ]

    if (this.createrType === 'MERCHANT' || this.createrType === 'ADMIN') {
      this.rules.cooperationUrl = [
        {
          required: true,
          message: '请上传合作协议',
        },
      ]
    }

    if (
      this.createrType === 'SELF_OPERATION_ADMIN' ||
      this.createrType === 'ADMIN'
    ) {
      this.rules.splitValue = [
        {
          required: true,
          validator: (rule, value, callback) => {
            let reg = /^[1-9]\d*$/
            if (!reg.test(value)) {
              callback(new Error('请输入整数!'))
            } else if (value < 0 || value > 100) {
              callback(new Error('请输入大于0且小于等于100的整数！'))
            } else {
              callback()
            }
          },
        },
      ]
    }

    getMerchantAllRoles({
      currentPage: 1,
      pageSize: 1000,
      userType: this.createrType,
    }).then((res) => {
      if (Array.isArray(res.list)) {
        const list = []
        res.list.forEach((item) => {
          const temp = {
            label: item.showName,
            value: item.id,
          }
          list.push(temp)
        })
        let index = formItem.findIndex((item) => item.value === 'roleId')

        if (index < 0) return

        if (this.createrType !== 'MERCHANT') {
          this.$set(formItem, index, {
            label: '运营商角色',
            type: 'select',
            options: list,
            value: 'roleId',
            required: true,
          })
        } else {
          formItem.splice(index, 1)
        }

        this.formItems = formItem
      }
    })

    if (this.isEdit) {
      this.getMerchantDetails()
    }
  },
  methods: {
    getMerchantDetails() {
      if (!this.$route.params.userId) return

      this.loading = true
      queryMerchant({ id: parseInt(this.$route.params.userId) })
        .then((res) => {
          // this.data = res
          console.log(res)
          const {
            userName,
            mobile,
            serviceMobile,
            address,
            roleId,
            name,
            splitValue,
            cooperationUrl,
            licenseUrl,
            province,
            city,
            district,
            id,
            splitCalcMethod,
          } = res
          this.form = {
            id,
            userName,
            mobile,
            serviceMobile,
            address,
            roleId,
            name,
            splitValue,
            cooperationUrl,
            licenseUrl,
            area: {
              province: parseInt(province),
              city: parseInt(city),
              district: parseInt(district),
            },
            splitCalcMethod,
          }
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleUserDefaultPwd(val) {
      this.form.confirmPassword = val
    },
    adminAddMerchant(params) {
      if (this.createrType === 'ADMIN') {
        params.type = 'MERCHANT'
      } else if (this.createrType === 'SELF_OPERATION_ADMIN') {
        params.type = 'SELF_OPERATION_MERCHANT'
      }

      this.loading = true
      updateMerchant(params)
        .then(() => {
          this.$message({
            showClose: true,
            message: '操作成功',
          })

          this.$router.push('/user/list')
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.loading = false
        })
    },
    merchantApplySub(params) {
      params.merchantType = 'ANOTHER'
      params.applyType = 'CREATE'

      params.newpassword = params.confirmPassword

      delete params.confirmPassword

      if (!this.$store.getters.userId) return

      this.loading = true
      subMerchantApply({
        ...params,
        createUserId: this.$store.getters.userId,
      })
        .then(() => {
          this.$message({
            showClose: true,
            message: '申请成功',
          })

          this.$router.push('/user/list')
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return

        let params = cloneDeep(this.form)
        if (params.area && params.area.province)
          params.province = params.area.province
        if (params.area && params.area.city) params.city = params.area.city
        if (params.area && params.area.district)
          params.district = params.area.district

        delete params.area

        if (params.splitValue) params.splitValue = Big(params.splitValue)

        if (params.password && params.confirmPassword) {
          params.password = md5(params.password)
          params.confirmPassword = md5(params.confirmPassword)
        }

        if (this.createrType !== 'MERCHANT') {
          this.adminAddMerchant(params)
        } else {
          this.merchantApplySub(params)
        }
      })
    },
    handleReset() {
      this.$refs.form.resetFields()
      // this.form = {}
      // this.$nextTick(() => {
      //   this.$refs.form.clearValidate()
      // })
    },
  },
}
</script>
<style lang="scss" scoped>
.user-merchant-add__submit {
  padding-top: 14px;
  padding-left: 20px;
}
.merchant-add__form {
  width: 35%;
}
</style>
